<template>
	<uw-dialog v-model="showModel">
		<template #title>{{props.goodsId ? '编辑' : '添加'}}商品</template>
		<template #default>
			<uw-form :data="formData" ref="uwFormRef" >
				<template #default>
					<el-tabs v-model="activeName">
						<el-tab-pane label="基础信息" name="1">
							<uw-form-item :data="formData.base"></uw-form-item>
						</el-tab-pane>
						<el-tab-pane label="规格信息" name="2">
							<uw-form-item :data="formData.spec"></uw-form-item>
							<!-- 单规格 -->
							<uw-single-spec-form :data="formData.singlespec" v-if="formData.spec.fields[0].value === 1" />
							<!-- 多规格 -->
							<uw-multi-spec-form v-if="formData.spec.fields[0].value === 2" ref="MultiSpecFormRef" />
						</el-tab-pane>
						<el-tab-pane label="商品详情" name="3">
							<uw-form-item :data="formData.detail"></uw-form-item>
						</el-tab-pane>
						<el-tab-pane label="售后信息" name="4">
							<uw-form-item :data="formData.sales"></uw-form-item>
						</el-tab-pane>
					</el-tabs>
				</template>
				<template #btn>
					<el-button @click="showModel = false">取消</el-button>
					<el-button type="primary" @click="submit">确定</el-button>
				</template>
			</uw-form>
		</template>
	</uw-dialog>
</template>

<script setup lang="ts">
	import { getGoodsConfigApi , addGoodsApi } from '@/api/goods';
	import uwSingleSpecForm from './SingleSpecForm.vue';
	import uwMultiSpecForm from './MultiSpecForm.vue';
	import { ref, watch } from 'vue';
	const props = defineProps({
		modelValue: {
			type: Boolean,
			default: false
		},
		goodsId: {
			type: [Number,String],
			default: 0
		}
	})
	const uwFormRef = ref()
	const emits = defineEmits(['update:modelValue'])
	const showModel = ref(props.modelValue)
	const activeName = ref('1')
	const formModel = ref({})
	const formData = ref<any>({
		base:{},
		detail:{},
		sales:{},
		spec:{}
	})
	watch(() => props.modelValue, (newVal:boolean) => {
		if(newVal){
			getGoodsConfigApi({
				goodsId: props.goodsId
			}).then((res)=>{
				console.log(res.data.goods);
				formData.value = res.data.goods
				showModel.value = newVal
				Object.keys(res.data.goods).forEach((key:string)=>{
					if(res.data.goods[key].fields){
						res.data.goods[key].fields.forEach((item:any)=>{
							formModel.value[item.name] = item.value
						})
					}
				})
			})
		}
		emits('update:modelValue', newVal)
	})
	watch(() => showModel.value, (newVal:boolean) => {
		if(!newVal){
			uwFormRef.value.resetForm()
		}
		emits('update:modelValue', newVal)
	})
	const submit = () => {
		const data = uwFormRef.value.submit()
		console.log(data)
		addGoodsApi(data).then((res)=>{
			console.log(res);
		})
	}
</script>

<style>
</style>